package com.github.codemperor.core.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author zl
 * 这里注意，feign需要配置
 * hystrix:
 *   command:
 *     default:
 *       execution:
 *         isolation:
 *           strategy: SEMAPHORE (这个必须配置，否则header转换不允许)
 */
@Slf4j
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request;
        try {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (NullPointerException e) {
            //被调环境中不存在request对象，则不往header里添加当前请求环境的header
            log.warn("[FeignInterceptor] request is not exist");
            return;
        }

        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }

        //TODO 这里记得加入网关请求id以及各个服务节点号
    }
}
